<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="850px">
    <el-form :model="formData" ref="formRef" :rules="formRules" vloading="formLoading">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.elder.name" disabled class="mr-1" />
            <el-button @click="clickChooseElder" :style="{ display: isEdit ? 'none' : 'block' }"
              >选择老人</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用药种类数" prop="medicineTypeNumber">
            <el-input v-model="formData.medicineTypeNumber" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddMedicine">添加药品</el-button>
      <el-button @click="clickDeleteMedicine">删除药品</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      save-key="HealthMedicinePlanEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <template #medicineType="{ row }">
        {{ getDictObj(DICT_TYPE.HEALTH_MEDICINE_TYPE, row.medicine.medicineType).label }}
      </template>
      <template #medicineDosageForm="{ row }">
        {{
          getDictObj(DICT_TYPE.HEALTH_MEDICINE_DOSAGE_FORM, row.medicine.medicineDosageForm).label
        }}
      </template>
      <template #dayRate="{ row }">
        <InputNumber v-model="row.dayRate" class="!w-80px" />
      </template>
      <template #timeRate="{ row }">
        <InputNumber v-model="row.timeRate" class="!w-80px" />
      </template>
      <template #number="{ row }">
        <InputNumber v-model="row.number" class="!w-80px" type="decimal" />
      </template>
      <template #remark="{ row }">
        <el-input v-model="row.remark" />
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <HealthMedicineSelect ref="healthMedicineSelectRef" @select-value="handleSelectHealthMedicine" />
  <ElderInfoSelect ref="elderInfoSelectRef" @row-dblclick="handleSelectElderInfo" />
</template>
<script setup name="HealthMedicinePlanEdit" lang="ts">
import { DICT_TYPE, getDictObj } from '@/utils/dict'
import HealthMedicineSelect from '@/views/health/healthMedicine/HealthMedicineSelect.vue'
import ElderInfoSelect from '@/views/elder/elderInfo/ElderInfoSelect.vue'
import * as HealthMedicinePlanApi from '@/api/health/medicinePlan'
import * as HealthMedicinePlanModel from '@/model/health/medicine/HealthMedicinePlan'
import * as HealthMedicinePlanDetailModel from '@/model/health/medicine/HealthMedicinePlanDetail'
interface HealthMedicinePlanDetailEdit
  extends HealthMedicinePlanDetailModel.HealthMedicinePlanDetail {
  medicine: {
    medicineName: string
    medicineBrevityCode: string
    medicineSpecification: string
    medicineDosageForm: string
  }
  operateType: string
}
interface HealthMedicinePlanEdit extends HealthMedicinePlanModel.HealthMedicinePlan {
  elder: { name: string }
  medicineTypeNumber: number
  details: HealthMedicinePlanDetailEdit[]
}
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const { t } = useI18n()
const message = useMessage()
const formData = ref<HealthMedicinePlanEdit>({
  id: undefined,
  elder: { name: '' },
  elderId: undefined,
  medicineTypeNumber: 0,
  details: []
})
const formRules = reactive({
  elderName: [{ required: true, message: '请输入姓名', trigger: 'change' }]
})
const healthMedicineSelectRef = ref()
const elderInfoSelectRef = ref()
const tableCurrentRow = ref()
const isEdit = ref(false)
let formType = ''
const columns = [
  {
    label: '药品名称',
    prop: 'medicine.medicineName'
  },
  {
    label: '药品简码',
    prop: 'medicine.medicineBrevityCode'
  },
  {
    label: '药品类型',
    prop: 'medicine.medicineType',
    slot: 'medicineType'
  },
  {
    label: '药品规格',
    prop: 'medicine.medicineSpecification'
  },
  {
    label: '药品剂型',
    prop: 'medicine.medicineDosageForm',
    slot: 'medicineDosageForm'
  },
  {
    label: '天频率',
    prop: 'dayRate',
    slot: 'dayRate',
    minWidth: '100'
  },
  {
    label: '次频率',
    prop: 'timeRate',
    slot: 'timeRate',
    minWidth: '100'
  },
  {
    label: '数量',
    prop: 'number',
    slot: 'number',
    minWidth: '100'
  },
  {
    label: '备注',
    prop: 'remark',
    slot: 'remark'
  }
]

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    isEdit.value = true
    formLoading.value = true
    try {
      formData.value = await HealthMedicinePlanApi.singleGet(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    elder: { name: '' },
    elderId: undefined,
    medicineTypeNumber: 0,
    details: []
  }
  formRef.value?.resetFields()
  isEdit.value = false
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.details.length <= 0) {
    message.error('请选择药品')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as HealthMedicinePlanEdit
    if (formType === 'create') {
      await HealthMedicinePlanApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await HealthMedicinePlanApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch {
  } finally {
    formLoading.value = false
  }
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

/** 单击删除药品 */
const clickDeleteMedicine = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的药品')
    return
  }
  if (formType === 'create' || tableCurrentRow.value.id == '') {
    const index = formData.value.details.indexOf(tableCurrentRow.value)
    formData.value.details.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
  formData.value.medicineTypeNumber--
}

/** 单击新增药品 */
const clickAddMedicine = () => {
  healthMedicineSelectRef.value.open()
}

const clickChooseElder = () => {
  elderInfoSelectRef.value.open()
}

const handleSelectHealthMedicine = (selectMaterialStockList) => {
  selectMaterialStockList.forEach((element) => {
    const detail = {
      id: undefined,
      planId: formType === 'create' ? undefined : formData.value.id,
      dayRate: 1,
      timeRate: 1,
      medicineId: element.id,
      number: 1,
      remark: '',
      operateType: 'new',
      lastUseTime: '',
      medicine: {
        medicineName: element.medicineName,
        medicineBrevityCode: element.medicineBrevityCode,
        medicineType: element.medicineType,
        medicineSpecification: element.medicineSpecification,
        medicineDosageForm: element.medicineDosageForm
      }
    }
    formData.value.details.push(detail)
    formData.value.medicineTypeNumber++
  })
}

const handleSelectElderInfo = (selectElderInfo) => {
  formData.value.elder.name = selectElderInfo.name
  formData.value.elderId = selectElderInfo.id
}
</script>
